package trading.formulas.functions;

import java.util.Calendar;

import trading.Parameters;
import trading.data.Controller;
import trading.data.IDataType;
import trading.data.IStockTickDataCollection;


public class MA implements IFunction{

	/**
	 * parameters : cycle 
	 */
	private Parameters PARAM = new Parameters(new int[][]{{100,1,5,1}});
	
	final public static int CYCLE_IDX = 0;
	
	public static MA getMA()
	{
		return new MA();
	}
	
	private MA(){}
	
	private float getValue(IStockTickDataCollection dataCollection, String type, int index, int cycle, IDataFunctionProvider provider)
	{
		
		int period = index > cycle ? cycle : index;
		float sum = 0;
		for(int i = 0; i<period; i++)
		{
			sum += provider.getValue(type, dataCollection, index - i);
		}
		return sum/period;
	}

	@Override
	public Parameters getParameters() {
		return PARAM;
	}
	
	@Override
	public String getName() {
		return "MA";
	}

	@Override
	public float getValue(String dataType, IStockTickDataCollection dataCollection, int index) throws TradingFunctionException {

		return getValue(dataType, dataCollection, index, BasicFunctionProvider.INSTANCE);
	}
	
	@Override
	public float getValue(String dataType,
			IStockTickDataCollection dataCollection, int index,
			IDataFunctionProvider provider) {
		int cycle = getParameters().getParamValue(CYCLE_IDX);
		return getValue(dataCollection, dataType, index, cycle, provider);
	}
	
	public static void main(String[] args) {
		Calendar cal = Controller.createZeroCaledar();
		cal.set(2006, 05 - 1, 15);
		IStockTickDataCollection dataCollection = Controller.getTickData();
		int index = Controller.getIndex(dataCollection, cal, true);
		System.out.println(index);
//		index = 10;
		MA ma = MA.getMA();
		Parameters params = ma.getParameters();
		params.setParamValue(CYCLE_IDX, 10);
		System.out.println(ma.getValue(IDataType.CLOSE_NAME, dataCollection, index));
	}

}
